/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.ValidationTests.ACATS_3_0.Support;
using NUnit.Framework;
using Rhino.Mocks;

namespace NTasking.ValidationTests.ACATS_3_0.C9
{

    [TestFixture(Description = "")]
    public class C9A007A : ValidationTest
    {
        private static bool taskNotAborted = false;
        private static bool testValid = true;

        private static TType1 tObject1 = null;
        private static TType2 tObject2 = null;
        private static Register register = null;
        private static Secondary dependentByAccess = null;
        private static InnerTask innerTask = null;


        private class Register : ValidationTestTask
        {

            [Entry]
            internal Action Begin { get; private set; }


            [Entry]
            internal Action BirthsAndDeaths { get; private set; }


            [Entry]
            internal Action Sync1 { get; private set; }


            [Entry]
            internal Action Sync2 { get; private set; }


            internal Register(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void DeclarativePart()
            {
                tObject1 = new TType1(Result);
                tObject2 = new TType2(Result);
            }


            protected override void Body()
            {
                Accept(Begin);

                int oldCount = 0;

                for (int i = 0; i < 5; i++)
                {
                    if (Count(BirthsAndDeaths) == 2)
                        break;

                    Ada.Delay(10.0);

                }

                oldCount = Count(BirthsAndDeaths);

                if (oldCount == 2)
                {
                    // Allowing Abort#1
                    Accept(Sync1);

                    Ada.Delay(Impdef.ClearReadyQueue);

                    // CHECK THAT  #1  WAS ABORTED  -  3 WAYS:

                    try
                    {
                        tObject1.E();
                    }
                    catch (TaskingError)
                    {
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("OTHER EXCEPTION RAISED - 1");
                        Result.TestFailed();
                    }

                    if (tObject1.Callable)
                    {
                        Console.WriteLine("T_OBJECT1'CALLABLE = TRUE");
                        Result.TestFailed();
                    }

                    if (oldCount - Count(BirthsAndDeaths) != 1)
                    {
                        Console.WriteLine("TASK#1 NOT REMOVED FROM QUEUE");
                        Result.TestFailed();
                    }

                    oldCount = Count(BirthsAndDeaths);

                    // Allowing Abort#2
                    Accept(Sync2);

                    Ada.Delay(Impdef.ClearReadyQueue);

                    // CHECK THAT  #1  WAS ABORTED  -  3 WAYS:

                    try
                    {
                        tObject2.E();
                    }
                    catch (TaskingError)
                    {
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("OTHER EXCEPTION RAISED - 2");
                        Result.TestFailed();
                    }

                    if (tObject2.Callable)
                    {
                        Console.WriteLine("T_OBJECT2'CALLABLE = TRUE");
                        Result.TestFailed();
                    }

                    if (Count(BirthsAndDeaths) != 0)
                    {
                        Console.WriteLine("TASK#2 NOT REMOVED FROM QUEUE");
                        Result.TestFailed();
                    }

                }
                else
                {
                    Console.WriteLine("LINEUP NOT COMPLETE (AFTER 50 S.)");
                    testValid = false;
                }

                while (Count(BirthsAndDeaths) > 0)
                    Accept(BirthsAndDeaths);
            }
            protected override void Exception(Exception ex)
            {
                Console.WriteLine("Register threw " + ex.GetType().Name);
                Console.WriteLine(ex);
            }

        }


        private class Secondary : ValidationTestTask
        {

            [Entry]
            private Action WaitIndefinitely { get; set; }


            internal Secondary(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                register.Sync1();

                tObject1.Abort();

                Ada.Delay(0.0);

                Console.WriteLine("Secondary not Aborted");

                taskNotAborted = true;
            }

        }


        private class InnerTask : ValidationTestTask
        {

            [Entry]
            internal Action WaitIndefinitely { get; private set; }


            internal InnerTask(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                register.Sync2();

                tObject2.Abort();

                Ada.Delay(0.0);

                Console.WriteLine("InnerTask not Aborted");

                taskNotAborted = true;
            }

        }


        private class TType1 : ValidationTestTask
        {

            [Entry]
            internal Action E { get; private set; }


            internal TType1(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void DeclarativePart()
            {
                dependentByAccess = new Secondary(Result);
            }


            protected override void Body()
            {
                register.BirthsAndDeaths();

                Console.WriteLine("TType1 not Aborted");

                taskNotAborted = true;
            }

        }


        private class TType2 : ValidationTestTask
        {

            [Entry]
            internal Action E { get; private set; }


            internal TType2(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void DeclarativePart()
            {
                innerTask = new InnerTask(Result);
            }


            protected override void Body()
            {
                register.BirthsAndDeaths();

                Console.WriteLine("TType2 not Aborted");

                taskNotAborted = true;
            }

        }


        [Test(Description =
            "CHECK THAT A TASK MAY ABORT A TASK IT DEPENDS ON.")]
        public void Test()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();

            taskNotAborted = false;
            testValid = true;

            Ada.Declare(() =>
            {
                register = new Register(result);

                // Setup text expectations

                Expect.Call(result.TestFailed).Repeat.Never();
            },
            Begin: () =>
            {
                Expect.Call(() => result.TaskAborted(tObject1));
                Expect.Call(() => result.TaskAborted(tObject2));
                Expect.Call(() => result.TaskAborted(innerTask));
                Expect.Call(() => result.TaskAborted(dependentByAccess));
                Expect.Call(() => result.TaskFinished(register));

                Mocks.ReplayAll();

                // Start test execution

                register.Begin();
            });

            if (testValid && taskNotAborted)
            {
                Console.WriteLine("SOME TASKS NOT ABORTED");
                result.TestFailed();
            }
        }

    }

}
